package org.cyz.tools.core.assembly.treetable;



import com.alibaba.fastjson.JSONObject;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeTableColumn;
import javafx.scene.control.TreeTableView;
import javafx.scene.control.cell.TreeItemPropertyValueFactory;

import java.util.Iterator;

/**
 * @author abccy
 * @title: NewTreeTableViewCreator
 * @projectName RedisGUI
 * @description: TODO
 * @date 2020-8-171:01
 */
public class TreeTableViewCreator {
    public TreeTableViewCreator(){

    }

    @SuppressWarnings({ "unchecked" })
    //递归表行内容
    public TreeItem getNodeData(String jsonStr,int columnLengh,TreeItem fatherItem){
        jsonStr=jsonStr.replace("[","").replace("]","");
        JSONObject json = JSONObject.parseObject(jsonStr);
        int currentPropertyCount = DataBean.currentPropertyCount;
        String[] values = new String[currentPropertyCount];
        for(int i = 0;i < columnLengh;i++){
            values[i] = json.getJSONObject("nodeInfo")==null?"":json.getJSONObject("nodeInfo").get("data" + (i + 1))==null?"":json.getJSONObject("nodeInfo").get("data" + (i + 1)).toString();
        }
        for(int i = columnLengh;i < currentPropertyCount;i++){
            values[i] = "";
        }

        DataBean inventory = new DataBean(values);
        TreeItem treeItem = new TreeItem(inventory);
        if(fatherItem != null){
            fatherItem.getChildren().add(treeItem);
        }else{
            treeItem.setExpanded(true);
        }
        if(null!=json.getJSONArray("childNotes")){
            Iterator<Object> it = (json.getJSONArray("childNotes")).iterator();
            while(it.hasNext()){
                Object json2 = it.next();
                getNodeData(json2.toString(),columnLengh,treeItem) ;
            }
        }
        return treeItem;
    }

    @SuppressWarnings({ "unchecked"})
    public TreeTableView createContent(double layoutX, double layoutY, double width, double height, String[] columnName,
                                double minColumnWidth,String jsonMessage) {
        final TreeTableView treeTableView = new TreeTableView(getNodeData(jsonMessage,columnName.length,null));
        for (int i = 0; i < columnName.length; i++) {
            TreeTableColumn treeTableColumn = new TreeTableColumn(columnName[i]);
            treeTableColumn.setCellValueFactory(new TreeItemPropertyValueFactory("data" + (i + 1)));
            treeTableColumn.setMinWidth(minColumnWidth);
            treeTableView.getColumns().add(treeTableColumn);
        }

        treeTableView.setEditable(false);
        treeTableView.setLayoutX(layoutX);// X
        treeTableView.setLayoutY(layoutY);// Y
        treeTableView.setPrefSize(width, height);// Width Height
        return treeTableView;
    }

}
